#!/bin/bash
# Enrigin GStreamer Plugins - Build Script
# Usage: ./build_all.sh

set -e

# Color definitions
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# Get script directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"

echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}  Enrigin GStreamer Plugins Build${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""

# Step 1: Create build directory
echo -e "${YELLOW}[1/3] Creating build directory...${NC}"
cd "$PROJECT_DIR"
if [ -d "build" ]; then
    echo -e "${YELLOW}  Cleaning existing build directory...${NC}"
    rm -rf build
fi
mkdir build
cd build
echo -e "${GREEN}✓ Build directory created${NC}"
echo ""

# Step 2: Run CMake
echo -e "${YELLOW}[2/3] Running CMake...${NC}"
cmake .. > cmake_output.log 2>&1
if [ $? -eq 0 ]; then
    echo -e "${GREEN}✓ CMake configuration successful${NC}"
else
    echo -e "${RED}✗ CMake configuration failed${NC}"
    echo "Check cmake_output.log for details"
    exit 1
fi
echo ""

# Step 3: Build plugins
echo -e "${YELLOW}[3/3] Building plugins...${NC}"
make -j$(nproc) 2>&1 | tee build_output.log | grep -E "(Built target|error|warning|\[.*%\])" || true
echo ""

# Check build results
SUCCESS=true

if [ -f "libgstenrigindec.so" ]; then
    SIZE=$(stat -c%s "libgstenrigindec.so")
    echo -e "${GREEN}✓ enrigindec plugin built (${SIZE} bytes)${NC}"
else
    echo -e "${RED}✗ enrigindec plugin build failed${NC}"
    SUCCESS=false
fi

if [ -f "libgstenriginenc.so" ]; then
    SIZE=$(stat -c%s "libgstenriginenc.so")
    echo -e "${GREEN}✓ enriginenc plugin built (${SIZE} bytes)${NC}"
else
    echo -e "${RED}✗ enriginenc plugin build failed${NC}"
    SUCCESS=false
fi

if [ "$SUCCESS" = false ]; then
    echo ""
    echo -e "${RED}Build failed. Check build_output.log for details${NC}"
    exit 1
fi

# Summary
echo ""
echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}  Build Completed Successfully!${NC}"
echo -e "${GREEN}========================================${NC}"
echo ""
echo -e "${BLUE}Build artifacts:${NC}"
echo "  Decoder: $(pwd)/libgstenrigindec.so"
echo "  Encoder: $(pwd)/libgstenriginenc.so"
echo ""
echo -e "${BLUE}Next steps:${NC}"
echo "  1. Install plugins:"
echo "     sudo ../scripts/install.sh"
echo ""
echo "  2. Or test locally:"
echo "     export GST_PLUGIN_PATH=$(pwd):\$GST_PLUGIN_PATH"
echo "     gst-inspect-1.0 enrigindec"
echo "     gst-inspect-1.0 enriginenc"
echo ""
echo "  3. Run tests:"
echo "     cd ../tests"
echo "     ./test_enrigindec.sh"
echo "     ./test_enriginenc.sh"
echo ""
echo -e "${BLUE}Documentation:${NC}"
echo "  Quick start: ../QUICKSTART.md"
echo "  Full docs:   ../README.md"
echo ""
